﻿using System.IO;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using UserService.Domain.Aggregate.Address;
using UserService.Domain.Aggregate.User;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.Modeling;

namespace UserService.EntityFrameworkCore
{
    /// <summary>
    /// 用户服务数据库上下文
    /// </summary>
    public class UserServiceDbContext : AbpDbContext<UserServiceDbContext>
    {
        public DbSet<User> User { get; set; }
        public DbSet<Profile> Profile { get; set; }
        
        public UserServiceDbContext(DbContextOptions<UserServiceDbContext> options) : base(options) { }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            
            // 配置数据库实体
            modelBuilder.Entity<User>(u =>
            {
                u.ConfigureByConvention();
            });
            modelBuilder.Entity<Profile>(p =>
            {
                p.ConfigureByConvention();
                p.HasOne(profile => profile.User)
                    .WithOne(user => user.Profile)
                    .HasForeignKey<Profile>(profile => profile.Id);
            });
            modelBuilder.Entity<Address>(a =>
            {
                a.ConfigureByConvention();
            });
        }
    }
    
    public class LeoGeminiDbContextFactory : IDesignTimeDbContextFactory<UserServiceDbContext>
    {
        public UserServiceDbContext CreateDbContext(string[] args)
        {
            var configuration = BuildConfiguration();

            var builder = new DbContextOptionsBuilder<UserServiceDbContext>()
                .UseNpgsql(configuration.GetConnectionString("Default"));

            return new UserServiceDbContext(builder.Options);
        }
        
        public static IConfigurationRoot BuildConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false);
            return builder.Build();
        }
    }
}